﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.IO;
using System.Configuration;

namespace SmartAssembly {
    class Program {
        static Dictionary<string, string> arguments = new Dictionary<string, string>();
        static Regex asmRegex = new Regex(@"AssemblyName=""(?<AssemblyName>[^""]+)""",
            RegexOptions.Compiled | RegexOptions.IgnoreCase);
        static bool enabled = Boolean.Parse(ConfigurationManager.AppSettings["enabled"]);
        static void Main(string[] args) {
            if (!enabled) return;
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            foreach (var arg in args) {
                var tokens = arg.Split('=');
                var key = tokens[0].Substring(1);
                var value = tokens[1];
                arguments[key] = value;
            }
            var assemblyInfo = String.Format("{0}, Culture=neutral, PublicKeyToken=null",
                arguments["assembly"]);
            var assemblyFile = File.ReadAllText("PServiceBus.saproj");
            var assemblyName = asmRegex.Match(assemblyFile).Groups["AssemblyName"].Value;
            assemblyFile = assemblyFile.Replace(
                String.Format(@"AssemblyName=""{0}""", assemblyName),
                String.Format(@"AssemblyName=""{0}""",  assemblyInfo));
            File.WriteAllText("PServiceBus.saproj", assemblyFile);
            Process.Start(new ProcessStartInfo()
            {
                Arguments =
                       String.Format("/build \"PServiceBus.saproj\" /input=\"{0}\" /output=\"{1}\" ", 
                       arguments["input"], arguments["output"], arguments["assembly"]),
                FileName = @"C:\Program Files\Red Gate\SmartAssembly 6\SmartAssembly.com",
                UseShellExecute = false,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                RedirectStandardOutput = true
            }).WaitForExit();
        }
    }
}
